#include "thread.h"
#define ARG_MAX 10
char *get_cmd(char buff[], char *myargv[])
{
    if (buff == NULL || myargv == NULL)
        return NULL;
    int i = 0;
    char *ptr = NULL;
    char *s = strtok_r(buff, " ", &ptr);
    while (s != NULL)
    {
        myargv[i++] = s;
        s = strtok_r(NULL, " ", &ptr);
    }
    return myargv[0];
}
int run_cmd(int c, char *cmd, char *myargv[])
{
    int fd[2] = {0};
    if (pipe(fd) == -1)
    {
        printf("pipe err\n");
        send(c, "err1", 4, 0);
        return -1;
    }
    pid_t pid = fork();
    if (pid == -1)
    {
        printf("fork err\n");
        send(c, "err1", 4, 0);
        return -1;
    }
    if (pid == 0)
    {
        close(fd[0]);
        dup2(fd[1], 1);
        dup2(fd[1], 2);
        execvp(cmd, myargv);
        printf("cmd not find");
        exit(0);
    }
    close(fd[1]);
    wait(NULL);
    char send_buff[1024] = {"ok#"};
    int num = read(fd[0], send_buff + 3, 1020);
    send(c, send_buff, num + 3, 0);
    close(fd[0]);
}
void send_file(int c, char * name)
{
    if(NULL == name)
    {
        send(c, "err", 3, 0);
        return;
    }
    int fd = open(name, O_RDONLY);
    if(-1 == fd)
    {
        send(c, "err", 3, 0);
        return;
    }
    /* 输出文件大小 */
    int filesize = lseek(fd, 0, SEEK_END);
    lseek(fd, 0, SEEK_SET);
    char status[32] = {0};
    sprintf(status, "ok#%d", filesize);
    send(c, status, strlen(status), 0);
    memset(status, 0, 32);
    int num = recv(c, status, 31, 0);
    if(num <= 0)
    {
        printf("client closed\n");
        close(fd);
        return;
    }
    /* 客户端可能取消了下载的任务 */
    if(strcmp(status, "err")==0)
    {
        close(fd);
        return;
    }
    /* 给客户端发送数据 */
    char data[1024];
    num = 0;
    while((num = read(fd, data, 1024)) > 0)
    {
        send(c, data, num, 0);

    }
    close(fd);
}
void *work_thread(void *arg)
{
    int c = (int)arg;
    while (1)
    {
        char buff[128] = {0};
        int n = recv(c, buff, 127, 0);
        if (n <= 0)
        {
            break;
        }
        /*  printf("buff = %s\n",buff);
            send(c, "ok", 2, 0); */
        char *myargv[ARG_MAX] = {0};
        char *cmd = get_cmd(buff, myargv);
        if (strcmp(cmd, "get") == 0)
        {
            /* download */
            send_file(c, myargv[1]);    //myargv[1] is file's name
        }
        else if (strcmp(cmd, "up") == 0)
        {
            /* upload */
        }
        else
        {
            /* other code, exec the linux's exist func */
            if(run_cmd(c, cmd, myargv)==-1)continue;
        }
    }
    close(c);
    printf("client close");
}
void start_thread(int c)
{
    pthread_t id;
    pthread_create(&id, NULL, work_thread, (void *)c);
}